import { useAuth } from 'contexts/AuthContext';
import { yupResolver } from "@hookform/resolvers/yup";
import { countries } from "libs/countries";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import * as yup from "yup";

// MUI Components
import {
  Grid,
  FormControl,
  FormHelperText,
  MenuItem,
  InputAdornment,
  useTheme,
  Typography
} from '@mui/material';

// MUI Icons
import BusinessIcon from '@mui/icons-material/Business';
import PhoneIcon from '@mui/icons-material/Phone';
import LocationOnIcon from '@mui/icons-material/LocationOn';
import PublicIcon from '@mui/icons-material/Public';
import ReceiptIcon from '@mui/icons-material/Receipt';
import EmailIcon from '@mui/icons-material/Email';
import MarkEmailReadIcon from '@mui/icons-material/MarkEmailRead';
import BadgeIcon from '@mui/icons-material/Badge';

// Styled Components
import {
  StyledPaper,
  StyledTextField,
  StyledAppButton
} from "components/objects/StyledComponents";

const schema = yup.object().shape({
  companyName: yup.string().required(),
  companyPhone: yup.string().required(),
  companyBillingAddress: yup.string().required(),
  companyCountry: yup.string().required(),
  companyVat: yup.string().required(),
  companyEmail: yup.string().lowercase().email().required(),
  companySdi: yup.string(),
  companyPec: yup.string().lowercase().email().required(),
});

// Custom styled select component to match our other inputs
const StyledSelect = ({ darkMode, children, ...props }) => {
  return (
    <StyledTextField
      darkMode={darkMode}
      select
      fullWidth
      {...props}
    >
      {children}
    </StyledTextField>
  );
};

const AccountForm = ({ onSubmit }) => {
  const { user } = useAuth();
  const { t } = useTranslation();
  const theme = useTheme();
  const isDarkMode = theme.palette.mode === 'dark';

  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm({
    resolver: yupResolver(schema),
    defaultValues: {
      companyName: user.account.companyName,
      companyPhone: user.account.companyPhone,
      companyBillingAddress: user.account.companyBillingAddress,
      companyVat: user.account.companyVat,
      companySdi: user.account.companySdi,
      companyPec: user.account.companyPec,
      companyEmail: user.account.companyEmail,
      companyCountry: user.account.companyCountry,
    },
  });

  // Form field configuration to reduce repetition
  const formFields = [
    {
      name: "companyName",
      label: t("accountForm.companyName"),
      icon: <BusinessIcon />,
      required: true,
    },
    {
      name: "companyPhone",
      label: t("accountForm.phoneNumber"),
      icon: <PhoneIcon />,
      required: true,
    },
    {
      name: "companyBillingAddress",
      label: t("accountForm.billingAddress"),
      icon: <LocationOnIcon />,
      required: true,
    },
    {
      name: "companyVat",
      label: t("accountForm.vatNumber"),
      icon: <ReceiptIcon />,
      required: true,
    },
    {
      name: "companyEmail",
      label: t("Email"),
      icon: <EmailIcon />,
      type: "email",
      required: true,
    },
    {
      name: "companyPec",
      label: t("PEC"),
      icon: <MarkEmailReadIcon />,
      type: "email",
      required: true,
    },
    {
      name: "companySdi",
      label: t("SDI"),
      icon: <BadgeIcon />,
      required: false,
    },
  ];

  return (
    <StyledPaper darkMode={isDarkMode}>
      <form onSubmit={handleSubmit(onSubmit)}>
        <Grid container spacing={3}>
          {formFields.map((field) => (
            <Grid item xs={12} key={field.name}>
              <FormControl fullWidth>
                <Typography variant="subtitle2" sx={{ mb: 1 }}>
                  {field.label}
                </Typography>
                <StyledTextField
                  darkMode={isDarkMode}
                  fullWidth
                  type={field.type || "text"}
                  inputProps={{ maxLength: 256 }}
                  {...register(field.name, { required: field.required })}
                  error={!!errors[field.name]}
                  InputProps={{
                    startAdornment: field.icon && (
                      <InputAdornment position="start">
                        {field.icon}
                      </InputAdornment>
                    ),
                  }}
                />
                {errors[field.name] && (
                  <FormHelperText error>{errors[field.name].message}</FormHelperText>
                )}
              </FormControl>
            </Grid>
          ))}

          {/* Country select field - handled separately due to dropdown nature */}
          <Grid item xs={12}>
            <FormControl fullWidth>
              <Typography variant="subtitle2" sx={{ mb: 1 }}>
                {t("accountForm.companyCountry")}
              </Typography>
              <StyledSelect
                darkMode={isDarkMode}
                {...register("companyCountry", { required: true })}
                error={!!errors.companyCountry}
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <PublicIcon />
                    </InputAdornment>
                  ),
                }}
              >
                <MenuItem value="">{t("accountForm.selectOne")}</MenuItem>
                {countries.map((value, index) => (
                  <MenuItem key={index} value={value.code}>
                    {value.name} {value.flag}
                  </MenuItem>
                ))}
              </StyledSelect>
              {errors.companyCountry && (
                <FormHelperText error>{errors.companyCountry.message}</FormHelperText>
              )}
            </FormControl>
          </Grid>

          <Grid item xs={12} sx={{ mt: 2 }}>
            <StyledAppButton
              darkMode={isDarkMode}
              type="submit"
              fullWidth
              variant="contained"
              sx={{ py: 1.5 }}
            >
              {t("accountForm.update")}
            </StyledAppButton>
          </Grid>
        </Grid>
      </form>
    </StyledPaper>
  );
};

export default AccountForm;